<template>
  <div class="admin-profile">
    <div class="profile-header">
      <div class="avatar-container">
        <el-avatar :size="100" :src="avatarUrl" @error="handleAvatarError">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
        </el-avatar>
        <div class="upload-btn">
          <el-upload
            class="avatar-uploader"
            :http-request="uploadAvatar"
            action=""
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </div>
      </div>
      <div class="admin-info">
        <h2>{{ adminInfo && adminInfo.name ? adminInfo.name : '管理员' }}</h2>
        <p class="admin-role">{{ adminInfo && adminInfo.roleId ? getRoleName(adminInfo.roleId) : '系统管理员' }}</p>
        <p class="signature">{{ profile && profile.signature ? profile.signature : '系统管理员' }}</p>
      </div>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本资料" name="basic">
        <el-form :model="profile" ref="profileForm" label-width="100px" :rules="rules">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profile.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">保密</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="profile.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="个性签名" prop="signature">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="写一句话介绍自己"
              v-model="profile.signature">
            </el-input>
          </el-form-item>

          <el-form-item label="员工编号" prop="employeeId">
            <el-input v-model="profile.employeeId" placeholder="请输入员工编号"></el-input>
          </el-form-item>

          <el-form-item label="入职日期" prop="hireDate">
            <el-date-picker
              v-model="profile.hireDate"
              type="date"
              placeholder="选择入职日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="管理区域" prop="managedArea">
            <el-input v-model="profile.managedArea" placeholder="请输入管理区域"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="saveProfile">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="工作记录" name="workRecords">
        <div class="empty-data" v-if="!safeJobRecords.length">
          <el-empty description="暂无工作记录"></el-empty>
        </div>
        <div v-else>
          <div class="record-summary">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card shadow="hover">
                  <div slot="header">
                    <span>总上岗次数</span>
                  </div>
                  <div class="card-content">
                    <span class="number">{{ getTotalShifts() }}</span>
                    <span>次</span>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div slot="header">
                    <span>总工作时长</span>
                  </div>
                  <div class="card-content">
                    <span class="number">{{ getTotalWorkHours() }}</span>
                    <span>小时</span>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div slot="header">
                    <span>当前状态</span>
                  </div>
                  <div class="card-content">
                    <el-tag :type="getCurrentStatusType()">{{ getCurrentStatus() }}</el-tag>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <el-table
            :data="safeJobRecords"
            style="width: 100%; margin-top: 20px;">
            <el-table-column
              label="上岗时间"
              width="180">
              <template slot-scope="scope">
                {{ scope && scope.row && scope.row.startingDate ? scope.row.startingDate : '-' }}
              </template>
            </el-table-column>
            <el-table-column
              label="离岗时间"
              width="180">
              <template slot-scope="scope">
                {{ scope && scope.row && scope.row.laidOffTime ? scope.row.laidOffTime : '当前在岗' }}
              </template>
            </el-table-column>
            <el-table-column
              label="状态">
              <template slot-scope="scope">
                <el-tag :type="scope && scope.row && scope.row.onGuard ? 'success' : 'info'">
                  {{ scope && scope.row && scope.row.onGuard ? '在岗' : '离岗' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="工作时长">
              <template slot-scope="scope">
                {{ scope && scope.row ? calculateWorkHours(scope.row) : 0 }} 小时
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from '@/plugins/request/axios';

export default {
  name: 'AdminProfile',
  data() {
    return {
      activeTab: 'basic',
      profile: {
        account: '',
        avatar: '',
        gender: 0,
        birthday: '',
        signature: '',
        employeeId: '',
        hireDate: '',
        managedArea: '',
      },
      adminInfo: {
        account: '',
        name: '',
        phone: '',
        email: '',
        roleId: '',
        registerTime: '',
      },
      rules: {},
      jobRecords: [],
      avatarUrl: '',
      roles: [
        { id: 'ADMIN', name: '超级管理员', description: '拥有系统所有权限，可以进行所有操作。' },
        { id: 'MANAGER', name: '管理人员', description: '拥有大部分系统权限，负责日常管理工作。' },
        { id: 'OPERATOR', name: '运营人员', description: '负责系统日常运营和数据维护。' },
        { id: '1', name: '超级管理员', description: '拥有系统所有权限，可以进行所有操作。' },
        { id: '2', name: '管理人员', description: '拥有大部分系统权限，负责日常管理工作。' },
        { id: '3', name: '运营人员', description: '负责系统日常运营和数据维护。' },
        { id: 'admin', name: '超级管理员', description: '拥有系统所有权限，可以进行所有操作。' }
      ]
    };
  },
  computed: {
    safeJobRecords() {
      // 确保jobRecords始终是有效的数组
      return Array.isArray(this.jobRecords) ? this.jobRecords : [];
    }
  },
  created() {
    // 确保数据初始化为有效值
    this.profile = this.getDefaultProfile();
    this.adminInfo = this.getDefaultAdminInfo();
    this.jobRecords = [];

    // 尝试从API获取数据
    this.getAdminProfile();
    this.getAdminInfo();
    this.getJobRecords();

    // 添加调试方法到window对象，便于在控制台中测试
    window.debugAdminProfile = {
      component: this,
      testSave: async () => {
        try {
          const testData = {
            account: localStorage.getItem('adminId') || '',
            gender: 0,
            birthday: '2025-07-07',
            signature: '系统管理员',
            employeeId: '565621454',
            hireDate: '2025-07-20',
            managedArea: '黄家湖'
          };

          console.log("测试保存数据:", testData);

          // 测试直接使用axios发送请求
          const res = await axios({
            method: 'post',
            url: '/adminProfile/updateProfile',
            data: testData,
            headers: {
              'Content-Type': 'application/json'
            }
          });

          console.log("测试保存响应:", res);
          return res;
        } catch (error) {
          console.error("测试保存失败:", error);
          return error;
        }
      }
    };
  },
  methods: {
    formatAvatarUrl(url) {
      if (!url) return '';
      const isHttp = /^https?:\/\//i.test(url);
      if (isHttp) return url;
      const base = (axios && axios.defaults && axios.defaults.baseURL) ? axios.defaults.baseURL : '';
      if (!base) return url; // fallback
      return base.replace(/\/$/, '') + (url.startsWith('/') ? url : '/' + url);
    },
    async uploadAvatar(options) {
      try {
        const formData = new FormData();
        formData.append('file', options.file);
        const res = await axios.post('/adminProfile/uploadAvatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        const payload = res && res.data ? res.data : res;
        options.onSuccess && options.onSuccess(payload);
      } catch (e) {
        options.onError && options.onError(e);
      }
    },
    async getAdminProfile() {
      try {
        // 记录详细日志信息
        console.log("开始请求管理员个人资料，当前登录用户:", localStorage.getItem("adminId"));

        // 尝试从本地存储获取管理员账号
        const adminData = localStorage.getItem('userData');
        let adminAccount = '';
        if (adminData) {
          try {
            const userData = JSON.parse(adminData);
            adminAccount = userData.account || '';
            console.log("从localStorage获取的管理员账号:", adminAccount);
          } catch (e) {
            console.error("解析localStorage中的管理员信息失败:", e);
          }
        }
        //修改
        // 尝试直接请求API获取个人资料
        const res = await axios.get('/adminProfile/getAdminProfile');
        console.log("管理员个人资料请求响应:", res);

        if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
          this.profile = res.data.data || this.getDefaultProfile();
          this.avatarUrl = this.formatAvatarUrl(this.profile.avatar || '');
        } else {
          console.log('获取管理员个人资料返回非成功状态，尝试备选方案');

          // 如果API调用失败，尝试直接使用账号获取
          if (adminAccount) {
            try {
              const directRes = await axios.get(`/adminProfile/directGetProfile?account=${adminAccount}`);
              if (directRes.data && directRes.data.code === 200) {
                this.profile = directRes.data.data || this.getDefaultProfile();
                this.avatarUrl = this.formatAvatarUrl(this.profile.avatar || '');
                return;
              }
            } catch (e) {
              console.error("直接通过账号获取管理员个人资料失败:", e);
            }
          }

          // 使用默认数据
          this.profile = this.getDefaultProfile();
        }
      } catch (error) {
        console.error('获取个人资料失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
          console.error('请求头:', error.config && error.config.headers);
          console.error('请求路径:', error.config && error.config.url);
        }
        this.profile = this.getDefaultProfile();
      }
    },

    getDefaultProfile() {
      return {
        account: '',
        avatar: '',
        gender: 0,
        birthday: '',
        signature: '系统管理员',
        employeeId: '',
        hireDate: '',
        managedArea: '',
      };
    },

    async getAdminInfo() {
      try {
        console.log("开始获取管理员基本信息");
        const res = await axios.get('/admin/getAdminInfo');
        console.log("管理员基本信息响应:", res);

        if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
          this.adminInfo = res.data.data || this.getDefaultAdminInfo();
        } else {
          console.log("获取管理员基本信息返回非成功状态，使用默认数据");
          this.adminInfo = this.getDefaultAdminInfo();
        }
      } catch (error) {
        console.error('获取管理员信息失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        this.adminInfo = this.getDefaultAdminInfo();
      }
    },

    getDefaultAdminInfo() {
      return {
        account: localStorage.getItem('adminId') || '',
        name: '管理员',
        phone: '',
        email: '',
        roleId: '1',
        registerTime: new Date().toISOString(),
      };
    },

    async getJobRecords() {
      try {
        console.log("开始获取工作记录");
        const res = await axios.get('/admin/getJobRecords');
        console.log("工作记录响应:", res);

        if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
          this.jobRecords = res.data.data || [];
        } else {
          console.log("获取工作记录返回非成功状态，使用空数组");
          this.jobRecords = [];
        }
      } catch (error) {
        console.error('获取工作记录失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        this.jobRecords = [];
      }
    },
    async saveProfile() {
      try {
        this.$refs.profileForm.validate(async (valid) => {
          if (valid) {
            // 获取管理员账号
            let account = '';

            // 方法1：从localStorage中获取
            account = localStorage.getItem('adminId');
            console.log("从localStorage获取的管理员账号:", account);

            // 方法2：从profile中获取
            if (!account && this.profile && this.profile.account) {
              account = this.profile.account;
              console.log("从profile获取的管理员账号:", account);
            }

            // 方法3：从store中获取
            if (!account) {
              try {
                const store = this.$store || window.$store;
                if (store && store.userData && store.userData.account) {
                  account = store.userData.account;
                  console.log("从store获取的管理员账号:", account);
                }
              } catch (e) {
                console.error("从store获取管理员账号失败:", e);
              }
            }

            // 创建提交数据对象，只包含需要的字段
            const submitProfile = {
              account: account,
              gender: this.profile.gender,
              signature: this.profile.signature,
              department: this.profile.department,
              position: this.profile.position,
              employeeId: this.profile.employeeId,
              hireDate: this.profile.hireDate,
              managedArea: this.profile.managedArea
            };

            // 移除空值
            Object.keys(submitProfile).forEach(key => {
              if (submitProfile[key] === null || submitProfile[key] === undefined || submitProfile[key] === '') {
                delete submitProfile[key];
              }
            });

            // 检查是否有数据要提交
            if (Object.keys(submitProfile).length === 0) {
              this.$message.warning('没有要保存的数据');
              return;
            }

            // 检查必要字段
            if (!submitProfile.account) {
              // 如果所有方法都无法获取account，尝试从后端获取当前管理员信息
              try {
                const adminRes = await axios.get('/admin/getAdminInfo');
                if (adminRes.data && adminRes.data.code === 43000 && adminRes.data.data) {
                  submitProfile.account = adminRes.data.data.account;
                  console.log("从API获取的管理员账号:", submitProfile.account);
                }
              } catch (error) {
                console.error("获取管理员信息失败:", error);
              }

              if (!submitProfile.account) {
                this.$message.error('管理员账号不能为空，请重新登录');
                return;
              }
            }

            console.log("准备保存管理员个人资料:", submitProfile);

            try {
              const res = await axios({
                method: 'post',
                url: '/adminProfile/updateProfile',
                data: submitProfile,
                headers: {
                  'Content-Type': 'application/json'
                }
              });

              console.log("保存响应:", res);

              if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
                this.$message.success('个人资料更新成功');
                this.getAdminProfile(); // 重新获取个人资料
              } else {
                throw new Error(res.data?.msg || '保存失败');
              }
            } catch (error) {
              console.error("保存失败:", error);
              this.$message.error(error.message || '保存失败，请检查网络连接或联系管理员');
            }
          } else {
            return false;
          }
        });
      } catch (error) {
        console.error('保存个人资料失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
          console.error('请求URL:', error.config?.url);
          console.error('请求数据:', error.config?.data);
        }
        this.$message.error('保存个人资料失败，请检查网络连接或联系管理员');
      }
    },
    resetForm() {
      this.$refs.profileForm.resetFields();
      this.getAdminProfile();
    },
    getRoleName(roleId) {
      const role = this.roles.find(r => r.id === roleId);
      return role ? role.name : '系统管理员';
    },
    calculateWorkHours(record) {
      if (!record || !record.startingDate) return 0;

      try {
        const startTime = new Date(record.startingDate).getTime();
        if (isNaN(startTime)) return 0;

        const endTime = record.laidOffTime ? new Date(record.laidOffTime).getTime() : new Date().getTime();
        if (isNaN(endTime)) return 0;

        const hours = Math.round((endTime - startTime) / (1000 * 60 * 60));
        return hours > 0 ? hours : 0;
      } catch (error) {
        console.error('计算工作时长出错:', error);
        return 0;
      }
    },
    getCurrentStatus() {
      if (!this.safeJobRecords.length) return '离岗';
      const currentRecord = this.safeJobRecords.find(record => record && record.onGuard === true);
      return currentRecord ? '在岗' : '离岗';
    },
    getCurrentStatusType() {
      return this.getCurrentStatus() === '在岗' ? 'success' : 'info';
    },

    getTotalShifts() {
      return this.safeJobRecords.filter(record => record && record.onGuard === true).length;
    },

    getTotalWorkHours() {
      return this.safeJobRecords.reduce((total, record) => {
        return total + (record ? this.calculateWorkHours(record) : 0);
      }, 0);
    },

    handleAvatarSuccess(res) {
      try {
        const data = res && res.data !== undefined && res.code === undefined ? res.data : res;
        const code = (data && typeof data.code !== 'undefined') ? data.code : undefined;
        const avatar = (data && data.data) ? data.data : undefined;

        if (code === 200 || code === 43000) {
          if (avatar) {
            this.avatarUrl = this.formatAvatarUrl(avatar);
            this.profile.avatar = avatar;
          }
          this.$message.success('头像上传成功');
        } else {
          // 静默处理头像上传失败，不显示错误信息
          console.log('头像上传失败:', (data && data.msg) || '头像上传失败');
        }
      } catch (err) {
        console.error('解析上传响应失败:', err, res);
        // 静默处理头像上传失败，不显示错误信息
        console.log('头像上传失败');
      }
    },
    handleAvatarError() {
      // 头像加载失败时使用默认头像
      this.avatarUrl = 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png';
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG/PNG/WEBP格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>

<style scoped>
.admin-profile {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  min-height: 500px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-container {
  margin-right: 30px;
  text-align: center;
}

.upload-btn {
  margin-top: 10px;
}

.admin-info {
  flex-grow: 1;
}

.admin-role {
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin-top: 5px;
}

.signature {
  color: #606266;
  font-style: italic;
  margin-top: 5px;
}

.el-tabs {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.record-summary {
  margin-bottom: 20px;
}

.card-content {
  text-align: center;
  padding: 20px 0;
}

.number {
  font-size: 30px;
  font-weight: bold;
  color: #409EFF;
  margin-right: 5px;
}
</style>
